﻿using FreeSql.Internal.Model;
using Microsoft.AspNetCore.Mvc;
using orm.freesql.api.Entities;

namespace orm.freesql.api.Controllers
{
    /// <summary>
    /// 单表操作
    /// </summary>
    public class SingleController(IFreeSql freeSql) : FreeSqlBaseController(freeSql)
    {
        [HttpPost]
        public async Task<IActionResult> Insert()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                CreateTime = DateTime.Now
            };

            return Ok("Id：" + await FreeSql
                .Insert(order)
                .ExecuteIdentityAsync());
        }

        [HttpPatch]
        public async Task<IActionResult> Update(int id)
        {
            var order = new Order
            {
                Id = id,
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                TotalPrice = 1,
                CreateTime = DateTime.Now
            };

            return Ok(await FreeSql
                .Update<Order>()
                .SetSource(order)
                .ExecuteAffrowsAsync() > 0);
        }

        [HttpDelete]
        public async Task<IActionResult> Delete(int id)
        {
            return Ok(await FreeSql
                .Delete<Order>()
                .Where(o => o.Id == id)
                .ExecuteAffrowsAsync() > 0);
        }

        [HttpGet]
        public async Task<IActionResult> PageList(int pageIndex, int pageSize)
        {
            var pageInfo = new BasePagingInfo 
            {
                PageNumber = pageIndex,
                PageSize = pageSize
            };

            var orders = await FreeSql
                .Select<Order>()
                .Where(o => o.IsDeleted == false)
                .OrderByDescending(o => o.Id)
                .Page(pageInfo)
                .ToListAsync();

            return Ok(new { rows = orders, total = pageInfo.Count });
        }

        [HttpGet]
        public async Task<IActionResult> Detail(int id)
        {
            return Ok(await FreeSql
                .Select<Order>()
                .Where(o => o.Id == id)
                .FirstAsync());
        }
    }
}
